package org.eproject.core.well.viewhelp;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eproject.core.well.command.ICommand;
import org.eproject.core.well.exception.CommandException;
import org.eproject.core.well.exception.FactoryException;
import org.eproject.core.well.factory.Simplefactory;

public class Helper extends Abstracthelp {
	private HttpServletRequest req;
	private HttpServletResponse res;

	public Helper(HttpServletRequest req, HttpServletResponse res) {
		this.req = req;
		this.res = res;
	}

	public HttpServletRequest getReq() {
		return req;
	}

	public HttpServletResponse getRes() {
		return res;
	}
	
	public Map<String,Object> getData(){
		Map<String,Object> map = req.getParameterMap();
		Set<String> set = map.keySet();
		Map<String,Object> data = new HashMap<String,Object>();
		String[] temp = null;
		for (Iterator<String> it = set.iterator(); it.hasNext();) {
			String keyname = (String) it.next();
			temp = (String[]) map.get(keyname);
			if (temp != null && temp.length == 1) {
				data.put(keyname, temp[0]);
			} else {
				data.put(keyname, temp);
			}
		}
		return data;
	}
	public ICommand findCommand()throws CommandException{
		String temp = this.req.getParameter("command");
		if(temp == null){			
			String url = req.getRequestURI();
			int start = url.lastIndexOf("/")==-1? 0 : url.lastIndexOf("/") + 1;
			int end = url.lastIndexOf(".");
			temp = url.substring(start,end);
		}
		System.out.println(temp);
		try {
			return (ICommand)Simplefactory.creatorBean(temp);
		} catch (FactoryException e) {
			e.printStackTrace();
			throw new CommandException(e);
		}
	}
}
